<?php

/**
 * This is the model class for table "contact_group".
 *
 * The followings are the available columns in table 'contact_group':
 * @property integer $id
 * @property string $name
 * @property integer $create_user_id
 *
 * The followings are the available model relations:
 * @property Contact[] $contacts
 * @property User $owner
 */
class ContactGroup extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @return ContactGroup the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'contact_group';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('name', 'required'),
            array('name', 'length', 'max' => 64),
            // The following rule is used by search().
            array('name', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            'contacts' => array(self::HAS_MANY, 'Contact', 'contact_group_id'),
            'owner' => array(self::BELONGS_TO, 'User', 'create_user_id'),
            'contactCount' => array(self::STAT, 'Contact', 'contact_group_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'name' => 'Name',
            'create_user_id' => 'Owner',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        $criteria = new CDbCriteria;

        $criteria->compare('name', $this->name, true);
        $criteria->compare('create_user_id', Yii::app()->user->id);

        return new CActiveDataProvider(get_class($this), array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Set the value of attributes 'create_user_id' before the form is validated.
     */
    protected function beforeValidate() {
        if ($this->isNewRecord) {
            $this->create_user_id = Yii::app()->user->id;
        }

        return parent::beforeValidate();
    }

}